package daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import org.springframework.stereotype.Repository;

import dao.UserDAO;
import model.User;

@Repository("userDAOImpl")
public class UserDAOImpl implements UserDAO {

	@Override
	public Boolean saveUser(User user){

		Connection conn;
		Boolean saved = false;
		String username = user.getUsername();
		String name = user.getName();
		String surname = user.getSurname();
		String password = user.getPassword();
		String email = user.getEmail();
		Date birthdate = user.getBirthdate();

		try {
			conn = util.DatabaseUtils.dbConnection();
			String query = "INSERT INTO Users (name, surname, username, password, email, birthdate) "
					+ "VALUES ("+name+" "+surname+" "+username+" "+password+" "+email+" "+birthdate+")";
			PreparedStatement  statement = conn.prepareStatement(query);
			saved = statement.execute();
		} catch (SQLException e) {
			System.out.println("Database error" + e.toString());
		} catch (Exception e) {
			System.out.println("Database error" + e.toString());
		}

		return saved;
	}

	@Override
	public Boolean login(User user){
		String username = user.getUsername();
		String password = user.getPassword();
		Boolean result = null;
		Connection conn;
		try {
			conn = util.DatabaseUtils.dbConnection();
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery("SELECT * FROM Users WHERE username="+username+" AND password="+password); 
			if(rs.next()){
				result=true;
			} else {
				result=false;
			}
		} catch (Exception e) {
			System.out.println("Error :"+e);
		}
		return result;
	}

	public User getUserInfo(User user){

		User newUser = null;
		String username = user.getUsername();
		String password = user.getPassword();
		Boolean result = null;
		Connection conn;
		try {
			conn = util.DatabaseUtils.dbConnection();
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery("SELECT * FROM Users WHERE username="+username+" AND password="+password); 
			if(rs.next()){
				newUser.setUsername(username);
				newUser.setPassword(password);
				newUser.setName(rs.getString("name"));
				newUser.setEmail(rs.getString("email"));
				newUser.setBirthdate(rs.getDate("birthdate"));
			}

		} catch (Exception e) {
			System.out.println("Error :"+e);
		}
		return newUser;
	}

}
